<?php declare(strict_types=1);


namespace App\Services\Refund\Strategy;

use App\Api\Controllers\Config\VbillConfigController;
use App\Exceptions\BizException;
use App\Models\Store;

class VbillRefundStrategy implements RefundStrategyInterface
{

    public function refundQuery(array $data): array
    {
        $store = Store::query()->where("store_id", $data["store_id"])->first();
        if (empty($store)) {
            throw new BizException("门店不存在");
        }


        $config = new VbillConfigController();
        $vbill_config = $config->vbill_config($store->config_id);
        if (!$vbill_config) {
            throw new BizException("随行付配置不存在请检查配置");
        }

        $vbill_merchant = $config->vbill_merchant($store->store_id, $store->pid);
        if (!$vbill_merchant) {
            throw new BizException("随行付商户号不存在");
        }

        $obj = new \App\Api\Controllers\Vbill\PayController();
        $dataQuery['notify_url'] = url('/api/vbill/refund_notify_url'); //回调地址
        $dataQuery['request_url'] = $obj->refund_url; //请求地址;
        $dataQuery['mno'] = $vbill_merchant->mno;
        $dataQuery['privateKey'] = $vbill_config->privateKey; //
        $dataQuery['sxfpublic'] = $vbill_config->sxfpublic; //
        $dataQuery['orgId'] = $vbill_config->orgId; //
        $dataQuery['out_trade_no'] = $data["out_trade_no"];
        $return = $obj->refund_query($dataQuery);
        $status = -1;
        $other_refund_no = $refund_detail = $refund_time = "";
        //退款成功
        if ($return["status"] == 1) {
            $status = 1;
//            ['respData']['tranSts']
            $other_refund_no = $return["data"]["respData"]["sxfUuid"] ?? "";
            $refund_detail = $return["data"]["respData"]["refundDetail"] ?? "";
            $refund_time = $return["data"]["respData"]["payTime"] ?? "";
        } //等待付款
        elseif ($return["status"] == 2) {
            $status = 0;
        } //订单失败关闭
        elseif ($return["status"] == 3) {
            //其他情况
            $status = -1;
        }
        return [
            "status" => $status,
            "other_refund_no" => $other_refund_no,
            "refund_detail" => $refund_detail,
            "refund_time" => $refund_time
        ];
    }

}